import httplib
from time import sleep
import time
from urllib import urlencode
from threading import Thread, Lock
import sys
from copy import deepcopy
from random import randint, uniform
from json import dumps

SEND_DELAY = 3
READ_DELAY = 3

submit_address = '/data/post'
security_code = 'n427yd48r2guy34s'
headers = {'Content-type': 'application/x-www-form-urlencoded'}
send_queue = []

def initDataSource():
    from serial import Serial
    dev = Serial('/dev/ttyACM0', 9600, timeout=1)
    dev.write(b'\n')
    k = dev.readline()
    return dev

def readFromSource(src):
    return src.readline().strip()

def generateRandomJSONData():
    a = {}
    a['sunlight'] = randint(10, 70)
    a['flame'] = randint(20, 90)
    a['temperature'] = randint(10, 95)
    a['gases'] = randint(10,95)
    a['timeStamp'] = int(time.time())
    a['human'] = randint(0,100) < 40
    return dumps(a)

def getConnection(host, port, strict):
    return httplib.HTTPConnection(host, port, strict)

def send(conn, data):
    body = urlencode({'code': security_code, 'submition': data})
    conn.request('POST', submit_address, body, headers)
    return conn.getresponse()

